<?php
/**
 * 用户统计模块
 * Created by PhpStorm.
 * User: yzh
 * Date: 2019/5/17
 * Time: 15:57
 */

namespace app\api\service;


use app\api\model\Behavior;
use app\api\model\WorkUser;
use app\api\model\WorkUserLog;
use app\api\model\WorkUserThumbsup;
use app\common\lib\Queue;
use app\api\model\ThirdApp;
use app\common\lib\Socket;
use app\lib\enum\BehaviorStatusEnum;
use app\lib\enum\MessageStatusEnum;
use app\server\controller\Push;

class Statistics
{
    /**
     * 插入消息信息
     * @param $time
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertLog($time){
        $thirdApp = ThirdApp::getThirdList();
        foreach ($thirdApp as $key=>$item){
            $data =  $this->getAllList($item->id,$time);
            if (!empty($data)){
               // $status =  $log->insertLog($data);
                Queue::getInstance()->sendToMQ('/queue/statistics',$data);
               //$this->insertQueue($thirdApp);
            }
        }
        //异步通知消费者
        $result = $this->consumeMessage();
        return $result;
    }

    /**
     * 消费数据
     * @return string
     */
    public function consumeMessage(){
        //通知消费者
        $array =[ 'function'=>'readQueue','args'=>['destination'=>'/queue/statistics']];
        $task = new Socket("tcp://127.0.0.1:27000",5);
        $task->asyncTask($array);
        return 'success';
    }

    /**
     * 获取用户排序结果
     * @param $wu_id
     * @param $t_id
     * @param $time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllUser($t_id,$wu_id,$time,$page,$size){
        $result = WorkUserLog::getList($t_id,$wu_id,$time,$page,$size);
        return $result;
    }

    /**
     * 我的排名
     * @param $wu_id
     * @param $time
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMyRank($wu_id,$time){
        $result = WorkUserLog::myRank($wu_id,$time);
        return $result;
    }

    /**
     * 插入行为
     * @param array $data
     * @return bool|int
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function insertData($data = []){
        $log = new WorkUserLog();
        $result = $log->insertLog($data);//插入排序计划
        $result->hidden(['work_user_info']);
        $status=  $this->insertBehavior(json_encode($result),$result->wu_id);//插入行为
        return $status;
    }

    /**
     * 获取所有排序结果
     * @param $t_id
     * @param $time
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllList($t_id,$time){
        $data = [];
        $user = WorkUser::getAllUserByStatus($t_id,$time);
        if (!$user->isEmpty()){
            $result = $user->toArray();
            $last_names = array_column($result,'users_count');
            array_multisort($last_names,SORT_DESC,$result);
            foreach ($result as $key=>$item){
                $data[$key]['t_id'] = $t_id;
                $data[$key]['wu_id'] = $item['id'];
                $data[$key]['work_user_info'] = json_encode(['id'=>$item['id'],'name'=>$item['name'],'position'=>$item['position'],'userimg'=>$item['userimg']]);
                $data[$key]['rank'] = $key+1;
                $data[$key]['user_num'] = $item['users_count'];
                $data[$key]['time_info'] = date('Y-m-d',$time[0]);
            }
        }
        return $data;
    }

    /**
     * 用户电站
     * @param $wu_id
     * @param $id
     * @return WorkUserThumbsup|array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function creatThumbsup($wu_id,$id){
        $data['log_id'] = $id;
        $data['wu_id'] = $wu_id;
        $info = WorkUserThumbsup::findThumbsup($id,$wu_id);
        if (empty($info)){
            $result = WorkUserThumbsup::creatThumbsup($data);
        }else{
            $result = 'error:你已经点过攒了';
        }
        return $result;
    }

    /**
     * 获取点赞列表
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getThumbsupList($id,$size,$page){
        $list = WorkUserThumbsup::getList($id,$size,$page);
        return $list;
    }

    /**
     * 插入行为
     * @param $statistics
     * @param $wu_id
     * @return bool|int
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function  insertBehavior($statistics,$wu_id){
        $data['url'] = request()->url();
        $data['user_id'] = $wu_id;
        $data['behavior_id'] = getRandChar(10);
        $data['wu_id'] = $wu_id;
        $info = $this->getTypeData($statistics);
        $data['type'] = $info['type'];
        $data['content'] = $info['content'];
        $data['weight'] = $info['weight'];
        $behaviorModel = new Behavior();
        $result = $behaviorModel->createBehavior($data);
        $workUser = WorkUser::getBaseInfo($wu_id);
        //推送结果
        $news = $this->getMassgeInfo($workUser,$wu_id,$result,$info['content']);
        $push = new Push($wu_id);
        $status =  $push->sendToClient($news);
        return $status;
    }

    /**
     * 获取推送消息格式
     * @param $data
     * @param $result
     * @param $content
     * @param $details
     * @return false|string
     */
    private function getMassgeInfo($data,$wu_id,$result,$content){
        $data = $data->toArray();
        $info['id'] = $wu_id;
        $info['url'] = $data['userimg']['url'];
        $info['nickname'] = $data['name'];
        $info['type'] = 'rank';
        $info['message_type'] = MessageStatusEnum::STATISTICS;//排名
        $info['times'] = $result->times;
        $info['content'] = $content;
        $info['year'] = date("Y-m-d H:i",$result->add_time);
        $info['stamp'] = strtotime($info['year']);
        return json_encode($info);
    }

    /**
     * 类型
     * @param $data
     * @return mixed
     */
    private function getTypeData($data){
        $info['weight'] = 0;
        $info['type'] = BehaviorStatusEnum::RANK;//排名行为分类
        $info['content'] = $data;
        $info['explain'] = '昨日获客数据';
        return $info;
    }

}